<script setup lang="ts">
defineOptions({
  name: "add"
});
import { ref, reactive, computed, onMounted } from "vue";
import type { FormInstance, FormRules } from "px-ui";
import { createAcidDrumBucket, updateAcidDrumBucket, queryAcidDrumBucket, queryGasNameList } from "@/api/modules/operation";
import { useRouterStoreHook } from "@/store/modules/router";
import dayjs from "dayjs";
import { useThrottleFn } from "@vueuse/core";
import { throttleDelay as delay } from "@/utils/constant";

const routerStore = useRouterStoreHook();

interface Props {
  // 弹框类型 add 新增   edit 编辑
  type: "add" | "edit";
  id: string;
}

const props = withDefaults(defineProps<Props>(), {});
const dialogTableVisible = defineModel({ type: Boolean, default: false });
const title = computed(() => (props.type === "add" ? "新增" : "编辑"));

interface RuleForm {
  operationDate: string;
  chemical: string;
  drumA: string;
  drumB: string;
  lotNumber: string;
  productionDate: string;
  expirationDate: string;
  operator: string;
  confirmor: string;
  bucketCapacity: string;
  remark: string;
}

const chemicalOptions = ref<Array<any>>([]);
const loading = ref<boolean>(false);
const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  operationDate: "",
  chemical: "",
  drumA: undefined,
  drumB: undefined,
  lotNumber: "",
  productionDate: "",
  expirationDate: "",
  operator: "",
  confirmor: "",
  bucketCapacity: undefined,
  remark: ""
});

const rules = reactive<FormRules<RuleForm>>({
  operationDate: [{ required: true, message: "请选择Date", trigger: "blur" }],
  chemical: [{ required: true, message: "请输入Chemical", trigger: "blur" }],
  drumA: [{ required: true, message: "请输入DrumA", trigger: "blur" }],
  drumB: [{ required: true, message: "请输入DrumB", trigger: "blur" }],
  lotNumber: [{ required: true, message: "请输入Lot Number", trigger: "blur" }],
  productionDate: [{ required: true, message: "请选择生产日期", trigger: "blur" }],
  expirationDate: [{ required: true, message: "请选择有效期", trigger: "blur" }],
  operator: [{ required: true, message: "请输入操作人", trigger: "blur" }],
  confirmor: [{ required: true, message: "请输入确认人", trigger: "blur" }],
  bucketCapacity: [{ required: true, message: "请输入满瓶量", trigger: "blur" }],
  remark: [{ required: false, message: "请输入备注", trigger: "blur" }]
});

const emits = defineEmits(["submit"]);

const delayDateDisabledDateFn = (d: Date) => {
  const timeStamp = new Date(d).getTime();
  if (ruleForm.productionDate && timeStamp < dayjs(ruleForm.productionDate).valueOf()) return true;
  return false;
};

const cancelHandler = () => {
  dialogTableVisible.value = false;
};

const submitHandler = useThrottleFn(async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true;
      const { id } = props;
      const params = { ...ruleForm };
      if (props.type === "add") {
        await createAcidDrumBucket(params, () => {
          loading.value = false;
        });
      } else if (props.type === "edit") {
        params["id"] = id;
        await updateAcidDrumBucket(params, () => {
          loading.value = false;
        });
      }
      loading.value = false;
      emits("submit");
      dialogTableVisible.value = false;
    } else {
      console.error("error submit!", fields);
    }
  });
}, delay);

const initOptions = async () => {
  const params = { gasType: "CHEMICAL" };
  const res = await queryGasNameList(params);
  chemicalOptions.value = res?.map(item => ({ label: item, value: item }));
};

const init = async () => {
  await initOptions();
  if (props.type === "edit") {
    const { id } = props;
    loading.value = true;
    const res = await queryAcidDrumBucket(id, () => {
      loading.value = false;
    });
    const {
      operationDate = "",
      chemical = "",
      drumA = "",
      drumB = "",
      lotNumber = "",
      productionDate = "",
      expirationDate = "",
      operator = "",
      confirmor = "",
      bucketCapacity = "",
      remark = ""
    } = res;
    ruleForm.operationDate = operationDate;
    ruleForm.chemical = chemical;
    ruleForm.drumA = drumA;
    ruleForm.drumB = drumB;
    ruleForm.lotNumber = lotNumber;
    ruleForm.productionDate = productionDate;
    ruleForm.expirationDate = expirationDate;
    ruleForm.operator = operator;
    ruleForm.confirmor = confirmor;
    ruleForm.bucketCapacity = bucketCapacity;
    ruleForm.remark = remark;
    loading.value = false;
  }
};

onMounted(async () => {
  await init();
});
</script>

<template>
  <px-dialog v-model="dialogTableVisible" :title="title" width="1000px">
    <px-form
      ref="ruleFormRef"
      v-loading="loading"
      :model="ruleForm"
      :rules="rules"
      inline
      label-width="100px"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <px-row :gutter="32">
        <px-col :span="12">
          <px-form-item label="Date" prop="operationDate">
            <px-date-picker
              v-model="ruleForm.operationDate"
              clearable
              type="datetime"
              :editable="false"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm:ss"
              :default-time="new Date(2000, 1, 1, 0, 0, 0)"
              placeholder="请选择Date"
            />
          </px-form-item>
        </px-col>

        <px-col :span="12">
          <px-form-item label="Chemical" prop="chemical">
            <px-select v-model="ruleForm.chemical" filterable clearable placeholder="请选择Chemical">
              <px-option v-for="item in chemicalOptions" :key="item.value" :label="item.label" :value="item.value" />
            </px-select>
          </px-form-item>
        </px-col>

        <px-col :span="12">
          <px-form-item label="DrumA" prop="drumA">
            <px-input
              v-model.trim.number="ruleForm.drumA"
              class="px-input-number-no-controls"
              type="number"
              clearable
              :min="0"
              placeholder="请输入DrumA"
            />
          </px-form-item>
        </px-col>

        <px-col :span="12">
          <px-form-item label="DrumB" prop="drumB">
            <px-input
              v-model.trim.number="ruleForm.drumB"
              class="px-input-number-no-controls"
              type="number"
              clearable
              :min="0"
              placeholder="请输入DrumB"
            />
          </px-form-item>
        </px-col>

        <px-col :span="12">
          <px-form-item label="Lot Number" prop="lotNumber">
            <px-input v-model.trim="ruleForm.lotNumber" clearable placeholder="请输入Lot Number" />
          </px-form-item>
        </px-col>

        <px-col :span="12">
          <px-form-item label="生产日期" prop="productionDate">
            <px-date-picker
              v-model="ruleForm.productionDate"
              clearable
              type="date"
              :editable="false"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :default-time="new Date(2000, 1, 1)"
              placeholder="请选择生产日期"
            />
          </px-form-item>
        </px-col>

        <px-col :span="12">
          <px-form-item label="有效期" prop="expirationDate">
            <px-date-picker
              v-model="ruleForm.expirationDate"
              clearable
              type="date"
              :editable="false"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :default-time="new Date(2000, 1, 1)"
              :disabled-date="delayDateDisabledDateFn"
              placeholder="请选择有效期"
            />
          </px-form-item>
        </px-col>

        <px-col :span="12">
          <px-form-item label="操作人" prop="operator">
            <px-input v-model.trim="ruleForm.operator" clearable placeholder="请输入操作人" />
          </px-form-item>
        </px-col>

        <px-col :span="12">
          <px-form-item label="确认人" prop="confirmor">
            <px-input v-model.trim="ruleForm.confirmor" clearable placeholder="请输入确认人" />
          </px-form-item>
        </px-col>

        <px-col :span="12">
          <px-form-item label="满瓶量" prop="bucketCapacity">
            <px-input
              v-model.trim.number="ruleForm.bucketCapacity"
              class="px-input-number-no-controls"
              type="number"
              clearable
              :min="0"
              placeholder="请输入满瓶量"
            />
          </px-form-item>
        </px-col>

        <px-col :span="24">
          <px-form-item label="备注" prop="remark">
            <px-input v-model.trim="ruleForm.remark" clearable type="textarea" maxlength="200" show-word-limit placeholder="请输入备注" />
          </px-form-item>
        </px-col>
      </px-row>
    </px-form>

    <template #footer>
      <span class="dialog-footer">
        <px-button @click="cancelHandler">取消</px-button>
        <px-button type="primary" :loading="loading" @click="submitHandler"> 确认 </px-button>
      </span>
    </template>
  </px-dialog>
</template>

<style lang="scss" scoped>
:deep(.px-form-item) {
  width: 100%;

  .px-form-item__content {
    .px-input-number .px-input__inner {
      text-align: left;
    }

    .px-input,
    .px-input-number,
    .px-select,
    .px-date-picker,
    .px-time-picker,
    .px-tree-select {
      width: 100%;
    }
  }
}
</style>
